//
//  TNSoundTranslateTableViewController.m
//  TravelNotes
//
//  Created by 黄锋 on 15/8/22.
//  Copyright (c) 2015年 王浩宇. All rights reserved.
//

#import "TNSoundTranslateTableViewController.h"
#import "TNTranslateTableViewCell.h"
#import "FMDB.h"
#import "TNTranslateHeadView.h"
#import "TNTranslateFootView.h"
#import "Macro.h"
#import <QuartzCore/QuartzCore.h>
#import "iflyMSC/IFlyMSC.h"
#import "TNLanuageTableViewController.h"
#import <AFNetworking.h>
#import "MBProgressHUD.h"

#define kTableName @"Translate"
#define kUrl @"http://openapi.baidu.com/public/2.0/bmt/translate?client_id=jxmbjt5uVUhh1e9VGN2AuyuY&from=auto"
#define kUrl1 @"&q=*&to=#"

@interface TNSoundTranslateTableViewController () <IFlyRecognizerViewDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

@property(nonatomic, strong) NSMutableArray *dataArr;
@property(nonatomic, strong) FMDatabase *db;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, strong) TNTranslateHeadView *headView;
@property(nonatomic, strong) TNTranslateFootView *footView;
@property(nonatomic, strong) NSArray *languageArray;
@property(nonatomic, strong) NSArray *language_codeArray;

@property(nonatomic, copy) NSString *srcString;

@property(nonatomic, strong) TNLanuageTableViewController *lanuageVC;

@property(nonatomic, strong) IFlyRecognizerView *iflyRecognizerView;

@property(nonatomic, strong) UIAlertView *alertView;

@property(nonatomic, strong) MBProgressHUD *hud;

@end

@implementation TNSoundTranslateTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _languageArray = @[@"中文", @"英语", @"日语", @"韩语", @"西班牙语", @"法语", @"泰语", @"阿拉伯语", @"俄罗斯语", @"葡萄牙语", @"德语", @"意大利语"];
    _language_codeArray  = @[@"zh", @"en", @"jp", @"kor", @"spa", @"fra", @"th", @"ara", @"ru", @"pt", @"de", @"it"];
    self.navigationItem.title = @"语音翻译";
    _srcString = @"auto";
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(endEditing)];
    [self.view addGestureRecognizer:tap];
    [self registerForKeyboardNotifications];
    [self initial];
    [self creatView];
    [self openDb];
}

- (void)endEditing
{
    [self.view endEditing:YES];
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification *)info
{
    NSDictionary *userInfo = [info userInfo];
    NSValue *value = userInfo[@"UIKeyboardFrameEndUserInfoKey"];
    CGFloat height = [value CGRectValue].size.height;
    CGRect rect = CGRectMake(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40);
    rect.origin.y -= height;
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval duration;
    [animationDurationValue getValue:&duration];
    [UIView animateWithDuration:duration animations:^{
      _footView.frame = rect;
    }];
}

- (void)keyboardWillBeHidden:(NSNotification *)info
{
    NSDictionary *userInfo = [info userInfo];
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval duration;
    [animationDurationValue getValue:&duration];
    [UIView animateWithDuration:duration animations:^{
        _footView.frame = CGRectMake(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40);
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initial
{
    //初始化语音识别控件
    self.iflyRecognizerView = [[IFlyRecognizerView alloc]initWithCenter:self.view.center];
    self.iflyRecognizerView.delegate = self;
    [self.iflyRecognizerView setParameter: @"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    //asr_audio_path保存录音文件名,默认目录是documents
    [self.iflyRecognizerView setParameter: @"asrview.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    //设置返回的数据格式为默认plain
    [self.iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
}

- (void)creatView
{
    _headView = [[TNTranslateHeadView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 40)];
    [self setButtonTitle];
    [_headView.button0 addTarget:self action:@selector(choseLanuageAction0:) forControlEvents:UIControlEventTouchUpInside];
    [_headView.button1 addTarget:self action:@selector(choseLanuageAction1:) forControlEvents:UIControlEventTouchUpInside];
    _headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_headView];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + 40, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 40 - 40) style:UITableViewStyleGrouped];
    [self.tableView registerClass:[TNTranslateTableViewCell class]forCellReuseIdentifier:@"TNTranslateTableViewCell"];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _footView = [[TNTranslateFootView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 40)];
    [_footView.button addTarget:self action:@selector(startListenning:) forControlEvents:UIControlEventTouchUpInside];
    _footView.tf.delegate = self;
    _footView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_footView];
}

- (void)setLanguage_code:(NSString *)language_code
{
    _language_code = language_code;
    [self setButtonTitle];
}

- (void)setButtonTitle
{
    for (int i = 0; i < _language_codeArray.count; i++) {
        NSString *str = _language_codeArray[i];
        if ([str isEqualToString:_language_code]) {
            [_headView.button1 setTitle:_languageArray[i] forState:UIControlStateNormal];
            return;
        }
    }
    [_headView.button1 setTitle:@"英语" forState:UIControlStateNormal];
}

- (TNLanuageTableViewController *)lanuageVC
{
    if (!_lanuageVC) {
        _lanuageVC = [[TNLanuageTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
    }
    return _lanuageVC;
}

- (void)choseLanuageAction0:(UIButton *)sender
{
    NSMutableArray *arr = [@[@"自动检测"] mutableCopy];
    [arr addObjectsFromArray:_languageArray];
    self.lanuageVC.lanuageArray = arr;
    self.lanuageVC.string = _headView.button0.titleLabel.text;
    __weak TNTranslateHeadView *headV = _headView;
    __weak NSArray *array = _languageArray;
    self.lanuageVC.choseBlock = ^(NSString *str) {
        [headV.button0 setTitle:str forState:UIControlStateNormal];
        if (![str isEqualToString:@"自动检测"]) {
            for (int i = 0; i < _languageArray.count; i++) {
                if ([str isEqualToString:array[i]]) {
                    _srcString = _language_codeArray[i];
                    break;
                }
            }
        } else {
            _srcString = @"auto";
        }
    };
    [self presentViewController:_lanuageVC animated:YES completion:nil];
}

- (void)choseLanuageAction1:(UIButton *)sender
{
    self.lanuageVC.lanuageArray = _languageArray;
    self.lanuageVC.string = _headView.button1.titleLabel.text;
    __weak TNTranslateHeadView *headV = _headView;
    __weak NSArray *array = _languageArray;
    self.lanuageVC.choseBlock = ^(NSString *str) {
        [headV.button1 setTitle:str forState:UIControlStateNormal];
        for (int i = 0; i < _languageArray.count; i++) {
            if ([str isEqualToString:array[i]]) {
                _language_code = _language_codeArray[i];
                break;
            }
        }
    };
    [self presentViewController:_lanuageVC animated:YES completion:nil];
}

- (void)openDb
{
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"FMDB.db"];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
//        NSLog(@"数据库打开失败");
    } else {
        if (![self isExistTable:kTableName]) {
            NSString *sql = [NSString stringWithFormat:@"CREATE TABLE Translate (dst text, src text)"];
            [_db executeUpdate:sql];
        } else {
            [self getDataArr];
        }
    }
}

- (void)getDataArr
{
    if (_dataArr) {
        [_dataArr removeAllObjects];
    } else {
        _dataArr = [NSMutableArray array];
    }
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM '%@'", kTableName];
    FMResultSet *rs = [_db executeQuery:sql];
    while ([rs next]) {
        NSString *dst = [rs stringForColumn:@"dst"];
        NSString *src = [rs stringForColumn:@"src"];
        TNTranslateModel *model = [[TNTranslateModel alloc] initWithDst:dst src:src];
        [_dataArr addObject:model];
    }
    [rs close];
    [self.tableView reloadData];
    if (_dataArr.count) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}


- (BOOL) isExistTable:(NSString *)tableName
{
    FMResultSet *rs = [_db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self getDataWith:textField.text];
    textField.text = nil;
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - IFlyRecognizerViewDelegate

- (void)startListenning:(UIButton *)sender
{
    [self.view endEditing:YES];
    [self.iflyRecognizerView start];
//    NSLog(@"开始识别");
}

//返回数据处理
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [NSMutableString new];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    //发送网络请求
    if (result.length && ![result isEqualToString:@"。"]) {
        [self.iflyRecognizerView cancel];
        
        _hud = [[MBProgressHUD alloc] initWithWindow:[UIApplication sharedApplication].keyWindow];
        [self.view addSubview:_hud];
        [_hud show:YES];

        [self getDataWith:result];
    }
}

- (void)getDataWith:(NSString *)str
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [kUrl stringByReplacingOccurrencesOfString:@"auto" withString:_srcString];
    NSString *url1 = [kUrl1 stringByReplacingOccurrencesOfString:@"*" withString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    if (!_language_code) {
        _language_code = @"en";
    }
    url1 = [url1 stringByReplacingOccurrencesOfString:@"#" withString:_language_code];
    url = [url stringByAppendingString:url1];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic0 = dic[@"trans_result"][0];
        TNTranslateModel *model = [[TNTranslateModel alloc] init];
        [model setValuesForKeysWithDictionary:dic0];
        NSString *sql = [NSString stringWithFormat:@"INSERT INTO '%@' (dst, src) VALUES ('%@','%@')", kTableName, model.dst, model.src];
        [_db executeUpdate:sql];
        [self getDataArr];
        [_hud removeFromSuperview];
        [_hud show:NO];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [_hud removeFromSuperview];
        [_hud show:NO];
        _alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络出错" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
        _alertView.delegate = self;
        [_alertView show];
        [self performSelector:@selector(alertViewRemove) withObject:self afterDelay:.5];
    }];
}

- (void)alertViewRemove
{
    [_alertView dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)onError:(IFlySpeechError *)error
{
//    NSLog(@"RecognizerView error : %@",error.errorDesc);
}


#pragma mark - TableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TNTranslateModel *model = _dataArr[_dataArr.count - indexPath.row - 1];
    CGFloat height;
    if (!model.height) {
        height  = [TNTranslateTableViewCell heightForCell:model];
        model.height = height;
    } else {
        height = model.height;
    }
    return height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TNTranslateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TNTranslateTableViewCell" forIndexPath:indexPath];
    TNTranslateModel *model = _dataArr[_dataArr.count - indexPath.row - 1];
    cell.model = model;
    [cell.button0 addTarget:self action:@selector(fullAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.button1 addTarget:self action:@selector(deleteAction:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

- (void)fullAction:(UIButton *)sender
{
    TNTranslateTableViewCell *cell = (TNTranslateTableViewCell *)[[[sender superview] superview] superview];
    UILabel *lable = [[UILabel alloc] initWithFrame:[UIScreen mainScreen].bounds];
    lable.text = cell.lable0.text;
    lable.backgroundColor = [UIColor colorWithRed:0x38/255.0 green:0xb0/255.0 blue:0xde/255.0 alpha:1.0];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.textColor = [UIColor blueColor];
    lable.numberOfLines = 0;
    lable.font = [UIFont systemFontOfSize:40];
    lable.userInteractionEnabled = YES;
    self.navigationController.navigationBarHidden = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLableAction:)];
    [lable addGestureRecognizer:tap];
    [self.view addSubview:lable];
}

- (void)tapLableAction:(UITapGestureRecognizer *)sender
{
    self.navigationController.navigationBarHidden = NO;
    [sender.view removeFromSuperview];
}

- (void)deleteAction:(UIButton *)sender
{
    TNTranslateTableViewCell *cell = (TNTranslateTableViewCell *)[[[sender superview] superview] superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    [_dataArr removeObjectAtIndex:_dataArr.count - indexPath.row - 1];
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM '%@' WHERE src = '%@' and dst = '%@'", kTableName, cell.lable1.text, cell.lable0.text];
    [_db executeUpdate:sql];
    [self.tableView reloadData];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
